# generate a simulated log-Gaussian Cox process
# 
# Author: guochun
###############################################################################

library(RandomFields)

rLGCP=function(en.filter,sigma2,alpha,N,plotdim,nu=0.5){
	sigma2true=sigma2
	covrdim=dim(en.filter$v)
	xcell=plotdim[1]/covrdim[2]
	ycell=plotdim[2]/covrdim[1]
	mu=log(N/sum(exp(en.filter$v+0.5*sigma2true)*xcell*ycell))
	xcol=seq(xcell/2,plotdim[1],xcell)
	yrow=seq(ycell/2,plotdim[2],ycell)
	if(nu!=Inf){
		Y <- GaussRF(x=xcol, y=yrow, model="matern", grid=TRUE,
				param=c(mean=0.0, variance=sigma2true, nugget=0.0, scale=alpha,nu=nu))
	}#else if(nu==1/2){
	#	Y <-GaussRF(x=xcol, y=yrow, model="exponential", grid=TRUE,
	#			param=c(mean=0.0, variance=sigma2true, nugget=0.0, scale=alpha))
	#}
	else{
		Y <- GaussRF(x=xcol, y=yrow, model="gauss", grid=TRUE,
				param=c(mean=0.0, variance=sigma2true, nugget=0.0, scale=alpha/sqrt(0.5)))
	}
		
	
	#Y <- GaussRF(x=xcol, y=yrow, model="exponential", grid=TRUE,
	#		param=c(mean=0.0, variance=sigma2true, nugget=0.0, scale=alpha))
	
	Yim <- as.im(list(x = xcol, y = yrow, z = Y))
	Lambda=en.filter
	Lambda$v=exp(mu+en.filter$v+Yim$v)
    #simulate inhomogeneous Poisson process with intensity function given by Lambda.
	X=rpoispp(Lambda)
	return(X)
}
